import { z } from "zod";
import { createTRPCRouter, protectedProcedure } from "../trpc";
import { TRPCError } from "@trpc/server";
import { nanoid } from 'nanoid';

export const courseInvitationsRouter = createTRPCRouter({
  // 创建邀请链接
  create: protectedProcedure
    .input(z.object({
      courseId: z.string(),
      expiresAt: z.date().optional(),
      maxUses: z.number().min(1).optional(),
    }))
    .mutation(async ({ ctx, input }) => {
      // 验证课程所有权
      const course = await ctx.db.course.findUnique({
        where: { id: input.courseId },
      });

      if (!course || course.teacherId !== ctx.session.user.id) {
        throw new TRPCError({
          code: "FORBIDDEN",
          message: "没有权限创建邀请链接",
        });
      }

      // 创建邀请码
      const code = nanoid(8);

      return ctx.db.courseInvitation.create({
        data: {
          code,
          courseId: input.courseId,
          expiresAt: input.expiresAt,
          maxUses: input.maxUses,
        },
      });
    }),

  // 通过邀请码加入课程
  join: protectedProcedure
    .input(z.object({
      code: z.string(),
    }))
    .mutation(async ({ ctx, input }) => {
      const invitation = await ctx.db.courseInvitation.findUnique({
        where: { code: input.code },
        include: { course: true },
      });

      if (!invitation || !invitation.isActive) {
        throw new TRPCError({
          code: "NOT_FOUND",
          message: "邀请链接无效",
        });
      }

      // 验证是否过期
      if (invitation.expiresAt && invitation.expiresAt < new Date()) {
        throw new TRPCError({
          code: "BAD_REQUEST",
          message: "邀请链接已过期",
        });
      }

      // 验证使用次数
      if (invitation.maxUses && invitation.usedCount >= invitation.maxUses) {
        throw new TRPCError({
          code: "BAD_REQUEST",
          message: "邀请链接已达到最大使用次数",
        });
      }

      // 检查是否已经加入课程
      const existingEnrollment = await ctx.db.enrollment.findUnique({
        where: {
          courseId_studentId: {
            courseId: invitation.courseId,
            studentId: ctx.session.user.id,
          },
        },
      });

      if (existingEnrollment) {
        throw new TRPCError({
          code: "BAD_REQUEST",
          message: "您已经加入了该课程",
        });
      }

      // 创建课程注册记录
      await ctx.db.$transaction([
        ctx.db.enrollment.create({
          data: {
            courseId: invitation.courseId,
            studentId: ctx.session.user.id,
          },
        }),
        ctx.db.courseInvitation.update({
          where: { id: invitation.id },
          data: { usedCount: { increment: 1 } },
        }),
      ]);

      return invitation.course;
    }),
}); 